<template>
	<div class="container">
		<div class="el-card is-always-shadow diygw-col-24">
			<div class="el-card__body">
				<div class="mb8">
					<el-form class="flex flex-direction-row flex-wrap" :model="queryParams" :rules="queryParamsRules" ref="queryForm" label-width="80px">
						<div class="flex diygw-col-0">
							<el-form-item class="diygw-el-rate" prop="title_like" label="标题">
								<el-input type="text" placeholder="请输入标题查询" v-model="queryParams.title_like"> </el-input>
							</el-form-item>
						</div>
						<div class="flex diygw-col-0">
							<el-button type="primary" @click="handleQuery"> <SvgIcon name="ele-Search" /> 搜索 </el-button> <el-button @click="resetQuery"> <SvgIcon name="ele-Refresh" /> 重置 </el-button>
						</div>
					</el-form>
				</div>
				<div class="mb8">
					<el-button type="primary" plain @click="onOpenAddModule"> <SvgIcon name="ele-Plus" />新增 </el-button> <el-button type="danger" plain :disabled="multiple" @click="onTabelRowDel"> <SvgIcon name="ele-Delete" />删除 </el-button>
				</div>
				<el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" stripe border current-row-key="id" empty-text="没有数据" style="width: 100%">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column label="置顶" prop="title" align="center">
						<template #default="scope"> <el-tag style="cursor: pointer" v-if="scope.row.sortnum > 0" type="error" @click="updatenumApi(scope.row)"> 取消置顶 </el-tag><el-tag style="cursor: pointer" @click="ordernumApi(scope.row)" v-else> 置顶 </el-tag> </template>
					</el-table-column>
					<el-table-column label="分类名称" prop="title" align="center"> </el-table-column>
					<el-table-column label="数据状态" prop="status" align="center">
						<template #default="scope"> <el-tag v-if="scope.row.status == 1"> 有效 </el-tag><el-tag v-else> 无效 </el-tag> </template>
					</el-table-column>
					<el-table-column label="备注" prop="remark" align="center"> </el-table-column>
					<el-table-column label="操作" align="center" fixed="right" width="180">
						<template #default="scope">
							<el-button type="primary" plain size="small" @click="onOpenEditModule(scope.row)"> <SvgIcon name="ele-Edit" />修改 </el-button> <el-button v-if="scope.row.id != 0" type="danger" plain size="small" @click="onTabelRowDel(scope.row)"> <SvgIcon name="ele-Delete" />删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页设置-->
				<div v-show="total > 0"><el-divider></el-divider> <el-pagination background :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" /></div>
			</div>
			<!-- 添加或修改参数配置对话框 -->
			<el-dialog :fullscreen="isFullscreen" width="800px" v-model="isShowDialog" destroy-on-close title="文章分类" draggable center>
				<template #header="{ close, titleId, titleClass }">
					<h4 :id="titleId" :class="titleClass">文章分类</h4>
					<el-tooltip v-if="!isFullscreen" content="最大化" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<FullScreen />
							</el-icon>
						</el-button>
					</el-tooltip>
					<el-tooltip v-if="isFullscreen" content="返回" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<Remove />
							</el-icon>
						</el-button>
					</el-tooltip>
				</template>
				<el-form class="flex flex-direction-row flex-wrap" :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
					<div class="flex diygw-col-24">
						<el-form-item
							:rules="[
								{
									required: true,
									trigger: 'blur',
									message: '不能为空哟'
								}
							]"
							class="diygw-el-rate"
							prop="title"
							label="分类名称"
						>
							<el-input type="text" placeholder="请输入分类名称" v-model="editForm.title"> </el-input>
						</el-form-item>
					</div>
					<div class="flex diygw-col-24">
						<el-form-item prop="img" class="diygw-el-rate" label="分类图片">
							<diy-uploadinput v-model="editForm.img" title="分类图片"></diy-uploadinput>
						</el-form-item>
					</div>
					<div class="flex diygw-col-24">
						<el-form-item prop="remark" class="diygw-el-rate" label="描述">
							<el-input type="textarea" rows="3" placeholder="请输入描述" v-model="editForm.remark"> </el-input>
						</el-form-item>
					</div>
					<div class="flex diygw-col-24">
						<el-form-item prop="status" class="diygw-el-rate" label="数据状态">
							<el-radio-group v-model="editForm.status">
								<el-radio v-for="item in editFormData.statusDatas" :key="item.value" :label="item.value">
									{{ item.label }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</div>
				</el-form>
				<template #footer>
					<div class="dialog-footer flex justify-center"><el-button @click="closeDialog"> 取 消 </el-button> <el-button type="primary" @click="onSubmit" :loading="saveloading"> 保 存 </el-button></div>
				</template>
			</el-dialog>
		</div>
		<div class="clearfix"></div>
	</div>
</template>

<script>
	import { useRouter, useRoute } from 'vue-router';
	import { storeToRefs } from 'pinia';
	import { useUserInfo } from '@/stores/userInfo';

	import { ElMessageBox, ElMessage } from 'element-plus';
	import { deepClone, changeRowToForm } from '@/utils/other';
	import { addData, updateData, delData, listData } from '@/api';

	import DiyUploadinput from '@/components/upload/uploadinput.vue';

	export default {
		components: {
			DiyUploadinput
		},
		data() {
			return {
				globalOption: {},
				userInfo: {},
				ordernum: {
					code: 200,
					msg: '设置成功'
				},
				updatenum: {
					code: 200,
					msg: '修改成功',
					data: {
						id: '1',
						sortnum: '0'
					}
				},
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 弹出层标题
				title: '',
				// 总条数
				total: 0,
				tableData: [],
				// 是否显示弹出层
				isFullscreen: false,
				isShowDialog: false,
				saveloading: false,
				editFormInit: {},
				queryParamsInit: {},

				editFormData: {
					statusDatas: [
						{ value: '1', label: '有效' },
						{ value: '2', label: '无效' }
					]
				},

				queryParams: {
					pageNum: 1,
					pageSize: 10,
					title_like: ''
				},

				queryParamsRules: {},

				editForm: {
					id: undefined,
					title: '',
					img: '',
					remark: '',
					status: '1'
				},

				editFormRules: {}
			};
		},
		methods: {
			getParamData(e, row) {
				row = row || {};
				let dataset = e.currentTarget ? e.currentTarget.dataset : e;
				if (row) {
					dataset = Object.assign(dataset, row);
				}
				return dataset;
			},
			navigateTo(e, row) {
				let dataset = this.getParamData(e, row);
				let { type } = dataset;
				if (type == 'page' || type == 'inner' || type == 'href') {
					this.router.push({
						path: dataset.url,
						query: dataset
					});
				} else if (typeof this[type] == 'function') {
					this[type](dataset);
				} else {
					ElMessage.error('待实现点击事件');
				}
			},
			async init() {},
			// 置顶 API请求方法
			async ordernumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/cms/cate/sortnum';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				let flag = await this.confirmFunction({ title: '确定置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let ordernum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.ordernum = ordernum;
				this.resetQuery();
			},
			// 设置为0 API请求方法
			async updatenumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/cms/cate/update';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				http_data.sortnum = 0;
				let flag = await this.confirmFunction({ title: '确定取消置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let updatenum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.updatenum = updatenum;
				this.resetQuery();
			},

			// confirm 自定义方法
			async confirmFunction(param) {
				param = param || {};
				let thiz = this;
				let title = param && (param.title || param.title == 0) ? param.title : thiz.title || '';
				return new Promise((resolve) => {
					ElMessageBox({
						message: title,
						title: '警告',
						showCancelButton: true,
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							resolve(true);
						})
						.catch(() => {
							resolve(false);
						});
				});
			},
			// 打开弹窗
			openDialog(row) {
				if (row.id && row.id != undefined && row.id != 0) {
					this.editForm = changeRowToForm(row, this.editForm);
				} else {
					this.initForm();
				}
				this.isShowDialog = true;
				this.saveloading = false;
			},

			// 关闭弹窗
			closeDialog(row) {
				this.mittBus.emit('onEditAdmintableModule', row);
				this.isShowDialog = false;
			},

			// 保存
			onSubmit() {
				const formWrap = this.$refs.editFormRef;
				if (!formWrap) return;
				formWrap.validate((valid, fields) => {
					if (valid) {
						this.saveloading = true;
						if (this.editForm.id != undefined && this.editForm.id != 0) {
							updateData('/cms/cate', this.editForm)
								.then(() => {
									ElMessage.success('修改成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						} else {
							addData('/cms/cate', this.editForm)
								.then(() => {
									ElMessage.success('新增成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						}
					} else {
						let message = '';
						if (fields && Object.keys(fields).length > 0) {
							let field = fields[Object.keys(fields)[0]];
							let messages = field.map((item) => {
								return item.message;
							});
							message = messages.join(',');
						}
						ElMessage.error('验证未通过！' + message);
					}
				});
			},
			// 表单初始化，方法：`resetFields()` 无法使用
			initForm() {
				this.editForm = deepClone(this.editFormInit);
			},
			/** 查询文章分类列表 */
			handleQuery() {
				this.loading = true;
				listData('/cms/cate', this.queryParams).then((response) => {
					this.tableData = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.queryParams = deepClone(this.queryParamsInit);
				this.handleQuery();
			},

			// 打开新增文章分类弹窗
			onOpenAddModule(row) {
				row = [];
				this.title = '添加文章分类';
				this.openDialog(row);
			},
			// 打开编辑文章分类弹窗
			onOpenEditModule(row) {
				this.title = '修改文章分类';
				this.initForm();
				this.openDialog(row);
			},
			/** 删除按钮操作 */
			onTabelRowDel(row) {
				let thiz = this;
				const id = row.id || this.ids;
				ElMessageBox({
					message: '是否确认删除选中的文章分类?',
					title: '警告',
					showCancelButton: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					return delData('/cms/cate', id).then(() => {
						thiz.handleQuery();
						ElMessage.success('删除成功');
					});
				});
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id);
				this.single = selection.length != 1;
				this.multiple = !selection.length;
			},

			//分页页面大小发生变化
			handleSizeChange(val) {
				this.queryParams.pageSize = val;
				this.handleQuery();
			},
			//当前页码发生变化
			handleCurrentChange(val) {
				this.queryParams.pageNum = val;
				this.handleQuery();
			}
		},
		async mounted() {
			this.router = useRouter();
			this.globalOption = useRoute().query;
			const stores = useUserInfo();
			const { userInfos } = storeToRefs(stores);
			this.userInfo = userInfos;
			await this.init();
			this.editFormInit = deepClone(this.editForm);
			this.queryParamsInit = deepClone(this.queryParams);
			this.handleQuery();
			this.mittBus.on('onEditAdmintableModule', () => {
				this.handleQuery();
			});
		},
		beforeUnmount() {
			this.mittBus.off('onEditAdmintableModule');
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		font-size: 12px;
	}
</style>
